package org.idea.spring.framework.event;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * @Author linhao
 * @Date created in 5:54 下午 2021/5/29
 */
public class ParentEventDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext(){
            @Override
            protected void onRefresh() throws BeansException {
                super.onRefresh();
                System.out.println("this is parentContext refresh");
            }
        };
        parentContext.setId("parentContext");
        parentContext.register(MyEvent.class);

        AnnotationConfigApplicationContext childContext = new AnnotationConfigApplicationContext();
        childContext.setId("childContext");
        childContext.register(MyEvent.class);

        parentContext.refresh();
        childContext.refresh();

        childContext.close();
        parentContext.close();
    }

    static class MyEvent implements ApplicationListener<ApplicationContextEvent> {

        @Override
        public void onApplicationEvent(ApplicationContextEvent event) {
            System.out.printf("监听到Spring应用上下文id is %s,event is %s \n",event.getApplicationContext().getId(),event.getClass().getSimpleName());
        }
    }
}
